<!-- 销售订单编辑弹窗 -->
<template>
  <div class="ele-body">
    <a-card :title="saleOrderModalApp.title" :bordered="false">
      <a-form
        ref="form2"
        :model="saleOrderModalApp.saleOrder"
        :rules="saleOrderModalApp.rules"
        :label-col="{md: {span: 7}, sm: {span: 24}}"
        :wrapper-col="{md: {span: 17}, sm: {span: 24}}">
        <a-row :gutter="16">

          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="桌号:" name="deskNum">
              <a-input-number
                v-model:value="saleOrderModalApp.saleOrder.deskNum"
                placeholder="请输入桌号"
                :min="0"
                :step="1"
                class="ele-fluid"
              ></a-input-number>
            </a-form-item>
          </a-col>

          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="销售价格:" name="price">
              <a-input-number
                v-model:value="saleOrderModalApp.saleOrder.price"
                placeholder="请输入销售价格"
                disabled="true"
                :min="0"
                :step="0.01"
                class="ele-fluid importanceI"></a-input-number>
            </a-form-item>
          </a-col>

<!--          <a-col :lg="6" :md="12" :sm="24" :xs="24">-->
<!--            <a-form-item label="销售时间:" name="saleDate">-->
<!--              <a-date-picker-->
<!--                v-model:value="saleOrderModalApp.saleOrder.saleDate"-->
<!--                placeholder="请选择销售时间"-->
<!--                value-format="YYYY-MM-DD H:m:s"-->
<!--                class="ele-fluid"/>-->
<!--            </a-form-item>-->
<!--          </a-col>-->


          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item :wrapper-col="{md: {offset: 6}}" style="margin-bottom: -20px">
              <!--class="ele-pull-right"-->
              <div v-if="saleOrderModalApp.display">
                <teleport to="#saleOrderEditModalFooter">
                  <div>
                    <a-space size="middle">
                      <a-button @click="saleOrderListApp.editModalShowing=false">取消
                      </a-button>
                      <a-button
                        type="primary"
                        @click="onSubmit(saleOrderModalApp.saleOrder)"
                        :loading="loading">提交
                      </a-button>
                      <!--<a-button v-if="!eid"
                                type="dashed"
                                @click="continueSubmit"
                                :loading="loading">继续提交
                      </a-button>-->
                    </a-space>
                  </div>
                </teleport>
              </div>
              <div v-if="!saleOrderModalApp.display">
                <a-space size="middle">
                  <a-button @click="onBack()">返回列表</a-button>
                  <a-button
                    type="primary"
                    @click="onSubmit(saleOrderModalApp.saleOrder)"
                    :loading="loading">提交
                  </a-button>
                  <!--<a-button v-if="!eid"
                            type="dashed"
                            @click="continueSubmit"
                            :loading="loading">继续提交
                  </a-button>-->
                </a-space>
              </div>

            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <vxe-toolbar>
      <template #buttons>
        <vxe-button @click="insertEvent(-1)">插入</vxe-button>
        <vxe-button @click="$refs.xTable.removeCheckboxRow()">删除</vxe-button>
<!--        <vxe-button icon="fa fa-save" @click="saveEvent">保存</vxe-button>-->
      </template>
    </vxe-toolbar>

    <vxe-table
      border
      show-overflow
      keep-source
      ref="xTable"
      max-height="400"
      :data="tableData"
      :edit-config="{trigger: 'click', mode: 'cell', icon: 'fa fa-pencil', showStatus: true}">
      <vxe-column type="checkbox" width="60"></vxe-column>

      <vxe-column field="name" title="菜谱" :edit-render="{}">
        <template #default="{ row }">
          <span>{{ row.name }}</span>
        </template>
        <template #edit="{ row }">
          <vxe-select v-model="row.name" @change="({ value, $event }) => {
                                                      row.name=value.name;
                                                      row.menuId=value.eid;
                                                      row.menuPrice=value.price;
                                                      row.price=row.menuPrice*row.amount;
                                                      calculateTotalPrice();
                                                  }"
                      transfer>
            <vxe-option v-for="item in menuList" :key="item.eid" :value="item" :label="item.name"></vxe-option>
          </vxe-select>
        </template>
      </vxe-column>
      <vxe-column field="amount" title="数量" :edit-render="{defaultValue: 1}">
        <template #edit="{ row }">
          <vxe-input @change="({ value, $event }) => {
            row.price=row.menuPrice*row.amount;
            calculateTotalPrice();
          }" v-model="row.amount" type="text"></vxe-input>
        </template>
      </vxe-column>
      <vxe-column field="price" title="价格" sortable :edit-render="{}">
        <template #edit="{ row }">
          <vxe-input v-model="row.price" type="text"></vxe-input>
        </template>
      </vxe-column>
    </vxe-table>


  </div>

</template>

<script>
import {defineComponent, inject, reactive, onMounted, ref} from 'vue'
import {useRoute, useRouter} from "vue-router"
import {SaleOrderService} from "@/views/restaurant/sale/saleOrder/saleOrderService";
import {VXETable} from 'vxe-table'
import {useStore} from "vuex";
import regions from 'ele-admin-pro/packages/regions.js';
import {VegetableMenuService} from "@/views/restaurant/sale/vegetableMenu/vegetableMenuService";

export default defineComponent({
  components: {},
  setup() {
    // 省市区数据
    const cityData = regions
    const route = useRoute();
    const router = useRouter();
    const store = useStore();
    let routeId = route.params.id;
    let saleOrderListApp = inject('saleOrderListApp', reactive({}));
    let saleOrderGrid=inject('saleOrderGrid',reactive({}));
    const saleOrderModalApp = reactive({
      id: null,
      saleOrder: {},
      isEdit: false,
      display: false
    });
    saleOrderModalApp.rules = {
      deskNum: [
        {
          required: true,
          type: 'number',
          message: '请输入桌号',
          trigger: 'blur'
        }
      ],
      price: [
        {
          required: true,
          type: 'number',
          message: '请输入销售价格',
          trigger: 'blur'
        }
      ],
      saleDate: [
        {
          required: false,
          type: 'string',
          message: '请输入销售时间',
          trigger: 'blur'
        }
      ],
    }

    onMounted(() => {
      //清理数据
      saleOrderModalApp.saleOrder = reactive({});
      findAllMenu();
      if (routeId) {//路由
        saleOrderModalApp.id = routeId;
        saleOrderModalApp.display = false;
        findSaleOrder(saleOrderModalApp.id);
      } else if (saleOrderListApp.editModalForEdit) {//修改弹窗
        saleOrderModalApp.id = saleOrderListApp.currentId;
        saleOrderModalApp.display = true;
      } else if (!saleOrderListApp.editModalForEdit && saleOrderListApp.addModalForEdit) {//新增弹窗
        saleOrderModalApp.display = true;

      } else {
        saleOrderModalApp.title = "新增";
      }
      if (saleOrderModalApp.id) findSaleOrder(saleOrderModalApp.id);
    })

    const findSaleOrder = (id) => {
      SaleOrderService.findSaleOrderForView(id).then((res) => {
        saleOrderModalApp.saleOrder = res.data;
        tableData.value=res.data.menuSaleRecords;
        //TODO:为编辑准备.
        saleOrderModalApp.title = "编辑 " + saleOrderModalApp.saleOrder.name;
      }).catch(error => {
        VXETable.modal.message({content: `查找出错，原因是：${error.message}`, status: 'error'});
      })
    }

    /*TODO:提交 新增&编辑*/
    const onSubmit = (data) => {
      // debugger;
      //当为数组时用逗号连接
      if (data.eid) {
        //修改
        changeOrderMenu(data.eid)
        SaleOrderService.updateSaleOrder(data).then((res) => {
          console.log(res);
          VXETable.modal.message({content: '操作成功', status: 'success'});
          setTimeout(onBack, 3000);
        }).catch(error => {
          VXETable.modal.message({content: `系统错误，原因是：${error.message}`, status: 'error'});
        })
      } else {
        //新增
        data.menuSaleRecords=xTable.value.getTableData().fullData
        console.log(data)
        SaleOrderService.saveSaleOrder(data).then((res) => {
          console.log(res);
          VXETable.modal.message({content: '操作成功', status: 'success'});
          setTimeout(onBack, 3000);
        }).catch(error => {
          VXETable.modal.message({content: `系统错误，原因是：${error.message}`, status: 'error'});
        })
      }
    }

    /*TODO:继续提交*/
    const continueSubmit = () => {
      VXETable.modal.message({content: 'error 提示', status: 'error'});
    }

    /*TODO:返回列表*/
    const onBack = () => {
      router.push(`/restaurant/sale/saleOrder`);
      store.dispatch('user/tabRemove', route.fullPath);

      setTimeout(() => {
        saleOrderGrid.value.commitProxy("query");
      }, 1500);
      saleOrderListApp.editModalShowing = false;
    }

    const xTable = ref({})

    const tableData = ref([])


    const menuList = ref([]);
    const findAllMenu = () => {
      // console.log("新增")
      let pageParams = {
        currentPage: 1,
        filters: {},
        orderBys: [],
        pageSize: 1000
      }
      VegetableMenuService.findVegetableMenus(pageParams).then((res) => {

        menuList.value = res.data.datas;
        console.log(menuList.value)
      })
    }
    const insertEvent = async (row) => {
      const $table = xTable.value
      const record = {
        sex: '1',
        // date12: '2021-01-01'
      }
      const {row: newRow} = await $table.insertAt(record, row)
      await $table.setActiveCell(newRow, 'name')
    }

    const getInsertEvent = () => {
      const $table = xTable.value
      const insertRecords = $table.getInsertRecords()
      console.log(insertRecords)
      VXETable.modal.alert(`新增：${insertRecords.length}`)
    }

    const getSelectionEvent = () => {
      const $table = xTable.value
      const selectRecords = $table.getCheckboxRecords()
      VXETable.modal.alert(`选中：${selectRecords.length}`)
    }

    const changeOrderMenu = (orderId) => {
      const $table = xTable.value
      const {insertRecords, removeRecords, updateRecords} = $table.getRecordset();
      let changeMenuRecordDto={
        "insertRecords":insertRecords,
        "removeRecords":removeRecords,
        "updateRecords":updateRecords,
        "orderId":orderId
      }
      SaleOrderService.changeOrderMenu(changeMenuRecordDto).then((res) => {
        console.log(res)
      })
    }
    const calculateTotalPrice = () => {
      var totalPrice = 0;
      // console.log("row", )
      xTable.value.getTableData().fullData.forEach(row=>{
        console.log("row"+row)
        totalPrice += row.price;
      })
      saleOrderModalApp.saleOrder.price=totalPrice;
    }
    return {
      cityData,
      routeId,
      saleOrderListApp,
      saleOrderModalApp,
      onSubmit,
      continueSubmit,
      onBack,
      xTable,
      tableData,
      insertEvent,
      getInsertEvent,
      getSelectionEvent,
      findAllMenu,
      menuList,
      changeOrderMenu,
      calculateTotalPrice
    }

  },
})
</script>

<style scoped>

</style>
